package com.cskaoyan.mall.pay.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.mall.pay.api.OrderPayApi;
import com.cskaoyan.mall.pay.constants.PayResultEnum;
import com.cskaoyan.mall.pay.constants.PayReturnCodeEnum;
import com.cskaoyan.mall.pay.constants.PaymentConstants;
import com.cskaoyan.mall.pay.dal.entitys.Payment;
import com.cskaoyan.mall.pay.dal.persistence.PaymentMapper;
import com.cskaoyan.mall.pay.dto.PaymentRequest;
import com.cskaoyan.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.cskaoyan.mall.pay.dto.alipay.AlipaymentResponse;
import com.cskaoyan.mall.pay.service.PayCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @auther cskaoyan
 * @date 2022/7/13:11:42
 */
@Service
@Slf4j
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Autowired
    PaymentMapper paymentMapper;

    @Autowired
    OrderPayApi orderPayApi;

    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {
        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        try {
            //  根据请求参数，获取支付二维码
            String codeFileName = payHelper.test_trade_precreate(request);
            if (codeFileName == null) {
                // 获取支付二维码失败
                alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
                alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
                return alipaymentResponse;
            }

            // 获取支付二维码成功
            alipaymentResponse.setQrCode(codeFileName);
            alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());

            // 在tb_payment表中插入对于待支付的订单的支付信息  TRADE_PROCESSING
            Payment payment = new Payment();
            payment.setOrderId(request.getTradeNo());
            payment.setProductName(request.getProductName());
            payment.setCreateTime(new Date());
            payment.setStatus(PayResultEnum.TRADE_PROCESSING.getCode());
            payment.setPayerUid(request.getUserId());
            payment.setPayerAmount(request.getOrderFee());
            payment.setOrderAmount(request.getTotalFee());
            payment.setPayerName(request.getUsername());
            payment.setPayWay(request.getPayChannel());
            payment.setRemark("支付宝支付");
            payment.setUpdateTime(new Date());

            int affectedRows = paymentMapper.insert(payment);
            if (affectedRows < 1) {
                alipaymentResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
                alipaymentResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            alipaymentResponse.setCode(PayReturnCodeEnum.SYSTEM_ERROR.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
            log.error("获取支付二维码发生错误"+e);
            ExceptionProcessorUtils.wrapperHandlerException(alipaymentResponse,e);
        }
        return alipaymentResponse;
    }

    @Override
    @Transactional
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {

        AlipayQueryRetResponse alipayQueryRetResponse = new AlipayQueryRetResponse();

        boolean success = payHelper.test_trade_query(request.getTradeNo());
        if (success) {
            // 修改tb_payment中对应订单的支付信息，TRADE_SUCCESS，支付成功时间，支付完成时间
            alipayQueryRetResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            alipayQueryRetResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());

            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId", request.getTradeNo());
            List<Payment> payments = paymentMapper.selectByExample(example);
            Payment payment = payments.get(payments.size() - 1);
            payment.setCompleteTime(new Date());
            payment.setPaySuccessTime(new Date());
            payment.setUpdateTime(new Date());
            payment.setStatus(PayResultEnum.TRADE_SUCCESS.getCode());
            int affectedRows = paymentMapper.updateByPrimaryKeySelective(payment);
            //  支付服务中 调用 订单服务
            PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
            payOrderSuccessRequest.setOrderId(request.getTradeNo());
            PayOrderSuccessResponse payOrderSuccessResponse = orderPayApi.payOrderSuccess(payOrderSuccessRequest);
            log.info("订单服务调用完成!!!!!");
            if (!OrderRetCode.SUCCESS.getCode().equals(payOrderSuccessResponse.getCode())){
                log.error("支付服务中，调用订单服务失败");
            }
            // 修改订单状态  已支付
            // 修改库存  根据订单id，查询出订单中所有的订单商品条目，根据每个订单商品的下单数量，扣减锁定库存lock_count
        } else {
            // 修改tb_payment中对应订单的支付信息，FAIL，支付完成时间
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId", request.getTradeNo());
            List<Payment> payments = paymentMapper.selectByExample(example);
            Payment payment = payments.get(payments.size() - 1);
            payment.setStatus(PayResultEnum.FAIL.getCode());
            payment.setCompleteTime(new Date());
            payment.setUpdateTime(new Date());
            int affectedRows = paymentMapper.updateByPrimaryKeySelective(payment);
            if (affectedRows < 1) {
                alipayQueryRetResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
                return alipayQueryRetResponse;
            }
            alipayQueryRetResponse.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
            alipayQueryRetResponse.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
        }
        return alipayQueryRetResponse;
    }
}
